import router from './router'
import type { RouteRecordRaw } from 'vue-router'
import { useAppStoreWithOut } from '@/stores/modules/app'
import { usePermissionStoreWithOut } from '@/stores/modules/permission'
import { getSysUserAndRoleInfoByToken } from '@/api/sysUser'
import { sysMenuTreeByToken } from '@/api/sysMenu'
import { settingStore } from '@/stores/modules/setting'
const routingMode = settingStore().getRoutingMode
// 引入i18n
import i18n from './i18n'
const { t } = i18n.global
// 引入进度条插件
import NProgress from 'nprogress'
// 引入对应css样式
import 'nprogress/nprogress.css'
// 修改进度条插件的配置
NProgress.configure({
  showSpinner: false
})
const permissionStore = usePermissionStoreWithOut()
const appStore = useAppStoreWithOut()
const whiteList = ['/login',] // 不重定向白名单
let listInfo = [] as any
router.beforeEach(async (to, from, next) => {
  NProgress.start()
  if (appStore.getToken || sessionStorage.getItem('token')) {
    if (to.path === '/login') {
      next()
    } else {
      if (appStore.getUserInfo?.roles) {
        next()
        return
      }
      await getSysUserAndRoleInfoByToken({}).then((res) => {
        appStore.setUserInfo(res.data)
      })
      if (routingMode === 'back-end') {
        listInfo = await sysMenuTreeByToken({ roles: appStore.getUserInfo?.roles })
      }
      await permissionStore.generateRoutes(routingMode, listInfo.data)
      await permissionStore.getAddRouters.forEach((route) => {
        router.addRoute(route as unknown as RouteRecordRaw) // 动态添加可访问路由表
      })
      next({ ...to, replace: true })
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/login`) // 否则全部重定向到登录页
    }
  }
})

router.afterEach((to) => {
  if (to?.meta?.i18nKey) {
    document.title = t(to?.meta?.i18nKey as string)
  } else if (to?.meta?.title) {
    document.title = to?.meta?.title
  } else {
    document.title = import.meta.env.VITE_APP_TITLE
  }

  NProgress.done()
})
